var form;
layui.use('form', function () {
	form = layui.form;

	//增加
	form.on('submit(addNode)', function (data) {
		console.log(JSON.stringify(data.field));
		addNode(data.field);
		return false;
	});
	//编辑
	form.on('submit(edit)', function (data) {
		console.log(JSON.stringify(data.field));
		editNode(data.field);
		return false;
	});
	//编辑
	form.on('submit(del)', function (data) {
		console.log(JSON.stringify(data.field) + '删除');
		deleteNode();
		return false;
	});
});
function addNode(data) {
	var newItemName = data.newItemName;
	var from = data.from;
	var remark = data.remark;
	let options = myChart.getOption();
	let nodesOption = options.series[0].data;
	let linksOption = options.series[0].links;
	if (newItemName === "") {
		alert("Please input name of newNode")
		return false
	}
	if (!selectInfo.state) {
		alert("Please choose a node")
		return false
	}
	var newItemCategory = selectInfo.category + 1;//需要增加的节点 级别是 选中节点+1
	let newNode = getItemData(newItemName, newItemCategory);//option.js中的方法

	if (isDuplicate(newItemName)) {
		alert("you could not have duplicate name")
		return false
	}
	let newLink = {
		source: selectInfo.name,
		target: newNode.name
	}

	newNode.itemStyle.opacity = 1
	linksOption.push(newLink)
	nodesOption.push(newNode)

	//option 缓存的数据 判断重复的时候有用到
	optionFromDB.series[0].data.push(newNode)
	optionFromDB.series[0].links.push(newLink)
	console.log(optionFromDB)

	//为了添加后 显示高亮 
	// selectInfo.state = false

	options.series[0].itemStyle.opacity = 0.3
	options.series[0].lineStyle.opacity = 0.3
	for (let m in nodesOption) {
		// nodesOption[m].itemStyle = {}
		if (nodesOption[m].name === newNode.name || nodesOption[m].name == selectInfo.name) {
			console.log(nodesOption[m])
			nodesOption[m].itemStyle.opacity = 1 //Generally，should break loop once target get ，but for opacity init every time、
			//break                    
		}
	}
	myChart.setOption(options);

	//更新添加的json
	var jsonNode = { name: newItemName, from: from, remark: remark, list: [] }
	setJson_add(json, selectInfo.name, jsonNode);
	console.log("json" + JSON.stringify(json));
}

/**
 * 更新json_add
 * @param {*} data  json
 * @param {*} selectName 当前选中节点
 * @param {*} newNode 需要新添加的节点
 */
function setJson_add(data, selectName, newNode) {
	if (data.name == selectName) {
		data.list.push(newNode);
		return;
	} else {
		if (data.list.length > 0) {
			data.list.forEach(function (item, index) {
				setJson_add(item, selectName, newNode);
			});
		}
	}
}

/**
 * 检查是否有重复节点
 * @param {*} searchName 
 */
function isDuplicate(searchName) {
	let nodes = optionFromDB.series[0].data
	for (let m in optionFromDB.series[0].data) {
		if (nodes[m].name === searchName) {

			return true
		}
	}

	return false
}

function deleteNode() {
	if (!selectInfo.state) {
		alert("Please choose a node")
	} else {
		let options = myChart.getOption();
		let nodesOption = options.series[0].data
		let linksOption = options.series[0].links

		let newsource = ''
		let tempLinks = optionFromDB.series[0].links



		if (selectInfo.index == 0) { //advise you put the root first in the options or do something to judge 
			alert("could not delete the root")
		} else {
			console.log('hasChild.........');
			if (jsonHasChild(json, selectInfo.name)) {
				alert("只能删除最末端节点");
				return;
			}

			for (let m in linksOption) {
				if (linksOption[m].target === selectInfo.name) {
					newsource = linksOption[m].source
					linksOption.splice(m, 1)
					tempLinks.splice(m, 1)
				}
			}

			for (let m in linksOption) {
				if (linksOption[m].source === selectInfo.name) {
					linksOption[m].source = newsource
					tempLinks[m].source = newsource

					let count = 0
					let searchName = linksOption[m].target
					for (let t in nodesOption) {
						if (nodesOption[t].name === searchName) {
							count++
							break
						}
					}
					if (count === 0) { //it will occur when tree contract it's up to you whether use the ”completeness“
						for (let s in tempData) {
							if (tempData[s].name === searchName) {
								nodesOption.push(tempData[s])
							}
						}
					}
					// linksNodes.push(linksOption[m].target);
				}
			}
			nodesOption.splice(selectInfo.index, 1)
			optionFromDB.series[0].data = optionFromDB.series[0].data.filter(node => node.name !== selectInfo.name)
			//	console.log(tempData)
			options.series[0].itemStyle.opacity = 1
			options.series[0].lineStyle.opacity = 1
			// selectInfo.state = false
			console.log(optionFromDB)
			myChart.setOption(options)

			//更新删除json
			setJson_del(json, selectInfo.name);
			console.log("json--del" + JSON.stringify(json))
		}
	}
}


/**
 * 更新json_del
 * @param {*} data  json
 * @param {*} selectName 当前选中节点
 */
function setJson_del(data, selectName) {
	if (data.list.length > 0) {
		data.list.forEach(function (item, index) {
			if (item.name == selectName) {
				data.list.splice(index, 1);
				return;
			} else if (item.list.length > 0) {
				setJson_del(item, selectName)
			}
		});
	}
}


/**
 * 判断json有没有子集
 */
var result = false;
function jsonHasChild(data, selectName) {
	var fianl_result = hasChild(data, selectName);
	result = false;
	return fianl_result;
}

/**
 * 判断json有没有子集
 */
function hasChild(data, selectName) {
	if (data.name == selectName) {
		if (data.list.length > 0) {
			console.log('return.........');
			result = true;
		}
	} else {
		if (data.list.length > 0) {
			data.list.forEach(function (item, index) {
				return hasChild(item, selectName);
			});
		}
	}
	return result;
}


function editNode(data) {
	var newItemName = data.newItemName;
	var from = data.from;
	var remark = data.remark;
	let options = myChart.getOption();
	let nodesOption = options.series[0].data;
	let linksOption = options.series[0].links;
	if (newItemName === "") {
		alert("Please input name")
		return false
	}
	if (!selectInfo.state) {
		alert("Please choose a node")
		return false
	}
	if (isDuplicate(newItemName)) {
		alert("you could not have duplicate name")
		return false
	}

	nodesOption.forEach(function (item, index) {
		if (item.name == selectInfo.name) {
			item.name = newItemName;//更改 edit的name
		}
	});

	linksOption.forEach(function (item, index) {
		if (item.source == selectInfo.name) {
			item.source = newItemName;//更改 edit的name
		} else if (item.target == selectInfo.name) {
			item.target = newItemName;//更改 edit的name
		}
	});

	//更新缓存的数据
	optionFromDB.series[0].data.forEach(function (item, index) {
		if (item.name == selectInfo.name) {
			item.name = newItemName;//更改 edit的name
		}
	});
	optionFromDB.series[0].links.forEach(function (item, index) {
		if (item.source == selectInfo.name) {
			item.source = newItemName;//更改 edit的name
		} else if (item.target == selectInfo.name) {
			item.target = newItemName;//更改 edit的name
		}
	});



	// selectInfo.state = false
	// options.series[0].itemStyle.opacity = 1
	// options.series[0].lineStyle.opacity = 1
	options.series[0].itemStyle.opacity = 0.3
	options.series[0].lineStyle.opacity = 0.3
	for (let m in nodesOption) {
		// nodesOption[m].itemStyle = {}
		if (nodesOption[m].name === newItemName) {
			console.log(nodesOption[m])
			nodesOption[m].itemStyle.opacity = 1 //Generally，should break loop once target get ，but for opacity init every time、
			//break                    
		}
	}
	myChart.setOption(options);

	//更新重新编辑json
	setJson_edit(json, selectInfo.name, data);
	console.log("json--updata" + JSON.stringify(json))
}

/**
 * 更新json_edit
 * @param {*} data  json
 * @param {*} selectName 当前选中节点
 * @param {*} newNodeName 更改后节点的名称
 */
function setJson_edit(data, selectName, newNode) {
	if (data.name == selectName) {
		data.name = newNode.newItemName;
		data.from = newNode.from;
		data.remark = newNode.remark;
		return;
	} else if (data.list.length > 0) {
		data.list.forEach(function (item, index) {
			if (item.name == selectName) {
				item.name = newNode.newItemName;
				item.from = newNode.from;
				item.remark = newNode.remark;
				// item = newNode;
				return;
			} else if (item.list.length > 0) {
				setJson_edit(item, selectName, newNode)
			}
		});
	}
}

function selectEle(params) {
	console.log(params.event.offsetX);
	console.log(params.event.offsetY);
	clearTimeout(TimeFn)
	TimeFn = setTimeout(() => {
		let options = myChart.getOption()
		let nodesOption = options.series[0].data
		let name = params.data.name
		let category = params.data.category
		options.series[0].itemStyle.opacity = 0.3
		options.series[0].lineStyle.opacity = 0.3
		for (let m in nodesOption) {
			// nodesOption[m].itemStyle = {}
			if (nodesOption[m].name === name) {
				console.log(nodesOption[m])
				selectInfo.name = name
				selectInfo.category = category
				selectInfo.index = m
				selectInfo.x = params.event.offsetX;
				selectInfo.y = params.event.offsetY

				selectInfo.state = true
				nodesOption[m].itemStyle.opacity = 1 //Generally，should break loop once target get ，but for opacity init every time
				preName = name //i.e. nodesOption[m].itemStyle = {} enable default opacity=1 
				initRight();
				// if (name === preName) {
				// 	selectInfo.state = false
				// 	options.series[0].itemStyle.opacity = 1
				// 	options.series[0].lineStyle.opacity = 1
				// 	preName = ""
				// 	//break
				// } else {
				// 	selectInfo.state = true
				// 	nodesOption[m].itemStyle.opacity = 1 //Generally，should break loop once target get ，but for opacity init every time
				// 	preName = name //i.e. nodesOption[m].itemStyle = {} enable default opacity=1 
				// 	initRight();
				// 	//break                                     //could locate by setting preM ，and just recover that node with a large number of nodes
				// }
			} else {
				nodesOption[m].itemStyle.opacity = 0.3
			}
		}
		myChart.setOption(options);
	}, 300)
}

/**
 * 选择node 右侧显示对应的数据
 */
var result_right = null;
function initRight() {
	var obj = getJsonNodeByName(json, selectInfo.name);
	result_right = null;
	if (obj) {
		$('#newItemName').val(obj.name);
		$('#remark').val(obj.remark);
		$('#from').val(obj.from);
		form.render('select');
	}
}
/**
 * 通过name 找到 json node
 */
function getJsonNodeByName(data, selectName) {
	if (data.name == selectName) {
		result_right = data;
	} else {
		if (data.list.length > 0) {
			data.list.forEach(function (item, index) {
				getJsonNodeByName(item, selectName);
			});
		}
	}
	return result_right;
}

function preProcess() {
	let data = optionFromDB.series[0].data
	let links = optionFromDB.series[0].links
	data.forEach(function (node) {
		node.isSpread = true
	})
	//other init operation you want
}


/**
 * 伸展收缩
 */
function spreadAndcontract(params) {
	clearTimeout(TimeFn)
	let options = myChart.getOption()
	let nodesOption = options.series[0].data
	let linksOption = options.series[0].links
	let tempLinks = optionFromDB.series[0].links
	let tempData = optionFromDB.series[0].data
	let name = params.data.name
	let count = 0

	function hasChild(tempName) {

		linksOption.forEach(function (node) {
			if (node.source === tempName) {
				for (let m in nodesOption) {
					if (nodesOption[m].name === node.target) { //hasChild=>contract
						count++
						nodesOption.splice(m, 1)
						hasChild(node.target)

					}

				}
			}
		})
		if (!count) { // noChild=>spread 展开
			//置灰所有节点
			for (let m in nodesOption) {
				if (nodesOption[m].name == name) {
					nodesOption[m].itemStyle.opacity = 1
				} else {
					nodesOption[m].itemStyle.opacity = 0.3
				}
			}
			let tempTarget = []
			tempLinks.forEach(function (node) {
				if (node.source === name) {
					tempTarget.push(node.target) //no use
					for (let m in tempData) {
						if (tempData[m].name === node.target) {
							let n = 0
							for (let m in nodesOption) {
								if (nodesOption[m].name === node.target) { //no use
									n++
								}
							}
							if (n === 0) {
								tempData[m].itemStyle.opacity = 1
								nodesOption.push(tempData[m])
							}
						}
					}
				}
			})
		}

	}
	hasChild(name)
	myChart.setOption(options)
}

/**
 * 背景点击事件
 */
function bg_click() {
	// if (selectInfo.state) {

	if (true) {
		// alert(123)
		refresh();
		selectInfo.state = false
	}
}

/**
 * 所有点正常显示----刷新
 */
function refresh() {
	var options2 = myChart.getOption()
	options2.series[0].itemStyle.opacity = 1
	options2.series[0].lineStyle.opacity = 1
	var nodesOption = options2.series[0].data
	for (let m in nodesOption) {
		nodesOption[m].itemStyle.opacity = 1
	}
	myChart.setOption(options2);
}